{% extends 'base.html' %}

{% block title %}编辑工单 - 维修管理系统{% endblock %}

{% block content %}
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title mb-0">编辑工单</h4>
                    {% if ticket.ticket_number %}
                    <small class="text-light">工单号: {{ ticket.ticket_number }}</small>
                    {% endif %}
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        
                        <div class="mb-3">
                            <label for="{{ form.title.id_for_label }}" class="form-label">工单标题</label>
                            {{ form.title }}
                            {% if form.title.errors %}
                            <div class="text-danger small">{{ form.title.errors }}</div>
                            {% endif %}
                        </div>

                        <div class="mb-3">
                            <label for="{{ form.description.id_for_label }}" class="form-label">问题描述</label>
                            {{ form.description }}
                            {% if form.description.errors %}
                            <div class="text-danger small">{{ form.description.errors }}</div>
                            {% endif %}
                        </div>

                        <div class="mb-3">
                            <label for="{{ form.priority.id_for_label }}" class="form-label">优先级</label>
                            {{ form.priority }}
                            {% if form.priority.errors %}
                            <div class="text-danger small">{{ form.priority.errors }}</div>
                            {% endif %}
                        </div>

                        <!-- 已选设备列表 -->
                        <div class="mb-3">
                            <label class="form-label">已选择的设备</label>
                            <div id="selected-assets-list" class="mb-3">
                                {% for asset in ticket.assets.all %}
                                <div class="selected-asset-item d-inline-block me-2 mb-2" data-asset-id="{{ asset.id }}">
                                    <span class="badge bg-primary p-2">
                                        {{ asset.name }} ({{ asset.model }})
                                        <button type="button" class="btn-close btn-close-white ms-1 remove-asset" 
                                                data-asset-id="{{ asset.id }}" aria-label="删除"></button>
                                    </span>
                                </div>
                                {% empty %}
                                <div class="text-muted">暂无选择的设备</div>
                                {% endfor %}
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="{{ form.assets.id_for_label }}" class="form-label">{{ form.assets.label }}</label>
                            {{ form.assets }}
                            {% if form.assets.errors %}
                            <div class="text-danger small">{{ form.assets.errors }}</div>
                            {% endif %}
                            <div class="form-text">{{ form.assets.help_text }}</div>
                            {% if not form.assets.queryset %}
                            <div class="alert alert-warning mt-2">
                                <small>您还没有分配任何设备。您可以选择创建新设备。</small>
                            </div>
                            {% endif %}
                        </div>

                        <!-- 新设备创建部分 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">或创建新设备</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="{{ form.new_device_name.id_for_label }}" class="form-label">{{ form.new_device_name.label }}</label>
                                            {{ form.new_device_name }}
                                            {% if form.new_device_name.errors %}
                                            <div class="text-danger">
                                                {% for error in form.new_device_name.errors %}
                                                {{ error }}
                                                {% endfor %}
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="{{ form.new_device_model.id_for_label }}" class="form-label">{{ form.new_device_model.label }}</label>
                                            {{ form.new_device_model }}
                                            {% if form.new_device_model.errors %}
                                            <div class="text-danger">
                                                {% for error in form.new_device_model.errors %}
                                                {{ error }}
                                                {% endfor %}
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="{{ form.new_device_serial.id_for_label }}" class="form-label">{{ form.new_device_serial.label }}</label>
                                            {{ form.new_device_serial }}
                                            {% if form.new_device_serial.errors %}
                                            <div class="text-danger">
                                                {% for error in form.new_device_serial.errors %}
                                                {{ error }}
                                                {% endfor %}
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="{{ form.new_device_type.id_for_label }}" class="form-label">{{ form.new_device_type.label }}</label>
                                            {{ form.new_device_type }}
                                            {% if form.new_device_type.errors %}
                                            <div class="text-danger">
                                                {% for error in form.new_device_type.errors %}
                                                {{ error }}
                                                {% endfor %}
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 图片管理部分 -->
                        {% if ticket.images.exists %}
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">管理图片</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">现有图片</label>
                                    <div class="image-gallery">
                                        <div class="row">
                                            {% for image in ticket.images.all %}
                                            <div class="col-md-4 col-sm-6 mb-3">
                                                <div class="image-item text-center position-relative">
                                                    <a href="{{ image.image.url }}" target="_blank" class="d-block">
                                                        <img src="{{ image.image.url }}" alt="工单图片 {{ forloop.counter }}" 
                                                             class="img-thumbnail" style="max-width: 100%; height: 120px; object-fit: cover;">
                                                    </a>
                                                    <small class="text-muted d-block mt-1">{{ image.description }}</small>
                                                    <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 delete-image-btn" 
                                                            data-image-id="{{ image.id }}">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endif %}

                        <!-- 新增图片上传 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">{% if ticket.images.exists %}添加更多{% else %}上传{% endif %}图片</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="images" class="form-label">选择图片</label>
                                    <input type="file" name="images" id="images" class="form-control" multiple 
                                           accept=".jpg,.jpeg,.png,.gif,.webp">
                                    <div class="form-text">支持 JPG, PNG, GIF, WebP 格式，每张图片最大 5MB，最多 10 张</div>
                                </div>
                                
                                <!-- 图片预览区域 -->
                                <div id="image-preview" class="mt-3 d-none">
                                    <label class="form-label">图片预览</label>
                                    <div class="row" id="preview-container"></div>
                                </div>
                            </div>
                        </div>

                        <!-- 隐藏的删除图片字段 -->
                        {% if ticket.images.exists %}
                        <input type="hidden" name="delete_images" id="delete_images" value="">
                        {% endif %}

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="submit" name="save_draft" class="btn btn-secondary me-md-2">
                                <i class="bi bi-save"></i> 保存草稿
                            </button>
                            <button type="submit" name="submit" class="btn btn-primary">
                                <i class="bi bi-send"></i> 提交申请
                            </button>
                            <a href="{% url 'tickets:ticket_list_mine' %}" class="btn btn-outline-secondary">
                                取消
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.container {
    max-width: 800px;
    margin: 20px auto;
}
.card {
    border: none;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
}
.card-header {
    background-color: #2c3e50;
    color: white;
    border-radius: 10px 10px 0 0 !important;
}
.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
}
.btn {
    border-radius: 5px;
}
.form-control {
    border-radius: 5px;
    border: 1px solid #ddd;
}
.form-control:focus {
    border-color: #3498db;
    box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 设备删除功能
    const selectedAssetsList = document.getElementById('selected-assets-list');
    
    if (selectedAssetsList) {
        selectedAssetsList.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-asset')) {
                e.preventDefault();
                
                const assetId = e.target.dataset.assetId;
                const assetItem = e.target.closest('.selected-asset-item');
                
                if (assetId && assetItem) {
                    // 从视觉上移除设备
                    assetItem.remove();
                    
                    // 从选择框中移除该设备
                    const assetSelect = document.querySelector('select[name="assets"]');
                    if (assetSelect) {
                        const optionToRemove = assetSelect.querySelector(`option[value="${assetId}"]`);
                        if (optionToRemove) {
                            optionToRemove.selected = false;
                        }
                    }
                    
                    // 如果没有已选设备了，显示提示信息
                    const remainingAssets = selectedAssetsList.querySelectorAll('.selected-asset-item');
                    if (remainingAssets.length === 0) {
                        selectedAssetsList.innerHTML = '<div class="text-muted">暂无选择的设备</div>';
                    }
                }
            }
        });
    }
    
    // 设备选择变化时更新已选设备列表
    const assetSelect = document.querySelector('select[name="assets"]');
    if (assetSelect) {
        assetSelect.addEventListener('change', function() {
            updateSelectedAssetsList();
        });
    }
    
    function updateSelectedAssetsList() {
        const selectedOptions = Array.from(assetSelect.selectedOptions);
        const selectedAssetsContainer = document.getElementById('selected-assets-list');
        
        if (selectedAssetsContainer && selectedOptions.length > 0) {
            let html = '';
            
            selectedOptions.forEach(option => {
                html += `
                    <div class="selected-asset-item d-inline-block me-2 mb-2" data-asset-id="${option.value}">
                        <span class="badge bg-primary p-2">
                            ${option.text}
                            <button type="button" class="btn-close btn-close-white ms-1 remove-asset" 
                                    data-asset-id="${option.value}" aria-label="删除"></button>
                        </span>
                    </div>
                `;
            });
            
            selectedAssetsContainer.innerHTML = html;
        } else if (selectedAssetsContainer) {
            selectedAssetsContainer.innerHTML = '<div class="text-muted">暂无选择的设备</div>';
        }
    }

    // 图片删除功能
    const deleteImageButtons = document.querySelectorAll('.delete-image-btn');
    const deleteImagesInput = document.getElementById('delete_images');
    const deletedImageIds = new Set();
    
    if (deleteImageButtons.length > 0 && deleteImagesInput) {
        deleteImageButtons.forEach(button => {
            button.addEventListener('click', function() {
                const imageId = this.dataset.imageId;
                const imageItem = this.closest('.col-md-4');
                
                if (imageId && imageItem) {
                    // 添加到删除集合
                    deletedImageIds.add(imageId);
                    
                    // 更新隐藏字段
                    deleteImagesInput.value = Array.from(deletedImageIds).join(',');
                    
                    // 视觉上移除图片
                    imageItem.remove();
                    
                    // 如果没有图片了，隐藏图片管理区域
                    const remainingImages = document.querySelectorAll('.image-item');
                    if (remainingImages.length === 0) {
                        const imageManagementCard = document.querySelector('.card:has(.delete-image-btn)');
                        if (imageManagementCard) {
                            imageManagementCard.remove();
                        }
                    }
                }
            });
        });
    }

    // 图片预览功能
    const imageInput = document.getElementById('images');
    const imagePreview = document.getElementById('image-preview');
    const previewContainer = document.getElementById('preview-container');
    
    if (imageInput && imagePreview && previewContainer) {
        imageInput.addEventListener('change', function(e) {
            const files = e.target.files;
            
            if (files.length > 0) {
                imagePreview.classList.remove('d-none');
                previewContainer.innerHTML = '';
                
                Array.from(files).forEach((file, index) => {
                    if (file.type.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const col = document.createElement('div');
                            col.className = 'col-md-3 col-sm-4 mb-2';
                            col.innerHTML = `
                                <div class="image-preview-item text-center">
                                    <img src="${e.target.result}" alt="预览图片 ${index + 1}" 
                                         class="img-thumbnail" style="max-width: 100%; height: 80px; object-fit: cover;">
                                    <div class="text-truncate small mt-1">${file.name}</div>
                                    <button type="button" class="btn btn-sm btn-danger mt-1 remove-preview-btn" 
                                            data-file-index="${index}">
                                        <i class="bi bi-x"></i>
                                    </button>
                                </div>
                            `;
                            previewContainer.appendChild(col);
                            
                            // 添加预览图片删除功能
                            const removeBtn = col.querySelector('.remove-preview-btn');
                            removeBtn.addEventListener('click', function() {
                                // 从FileList中移除文件
                                const dataTransfer = new DataTransfer();
                                Array.from(imageInput.files).forEach((f, i) => {
                                    if (i !== parseInt(this.dataset.fileIndex)) {
                                        dataTransfer.items.add(f);
                                    }
                                });
                                imageInput.files = dataTransfer.files;
                                
                                // 移除预览
                                col.remove();
                                
                                // 如果没有预览图片了，隐藏预览区域
                                if (previewContainer.children.length === 0) {
                                    imagePreview.classList.add('d-none');
                                }
                            });
                        };
                        reader.readAsDataURL(file);
                    }
                });
            } else {
                imagePreview.classList.add('d-none');
                previewContainer.innerHTML = '';
            }
        });
    }
    
    // 表单提交前验证
    const form = document.querySelector('form');
    if (form) {
        form.addEventListener('submit', function(e) {
            // 确保删除图片的ID正确设置
            if (deleteImagesInput && deletedImageIds.size > 0) {
                deleteImagesInput.value = Array.from(deletedImageIds).join(',');
            }
            
            // 可以在这里添加其他验证逻辑
        });
    }
});
</script>
{% endblock %}
